#pragma once
#include <iostream>
#include <string>
#include <random>
#include "../Connection.hpp"
#include "Request&&Response.hpp"
#include "../RoomPlayers.hpp"

extern std::unordered_map<std::string, Room *> rooms;
extern std::unordered_map<int, std::string> fd_to_room_number;
extern std::vector<std::vector<int>> _battlefield_rgb;
extern double g_countdown;

void InitCountDown(int num)
{
	switch (num)
	{
	case 2:
		g_countdown = 300.0;
		break;
	case 4:
		g_countdown = 300.0;
		break;
	case 8:
		g_countdown = 600.0;
		break;
	default:
		break;
	}
}

void InitBattlefieldColor(int num)
{
	int poscolor = 0;
	switch (num)
	{
	case 2:
	{
		for (int i = 0; i < _battlefield_rgb.size() / 2; i++)
		{
			for (int j = 0; j < _battlefield_rgb[0].size(); j++)
			{
				_battlefield_rgb[i][j] = poscolor;
			}
		}
		poscolor++;
		for (int i = _battlefield_rgb.size() / 2; i < _battlefield_rgb.size(); i++)
		{
			for (int j = 0; j < _battlefield_rgb[0].size(); j++)
			{
				_battlefield_rgb[i][j] = poscolor;
			}
		}
		poscolor++;
	}
	break;
	case 4:
	{
		for (int i = 0; i < _battlefield_rgb.size() / 2; i++)
		{
			for (int j = 0; j < _battlefield_rgb[0].size() / 2; j++)
			{
				_battlefield_rgb[i][j] = poscolor;
			}
		}
		poscolor++;
		for (int i = 0; i < _battlefield_rgb.size() / 2; i++)
		{
			for (int j = _battlefield_rgb[0].size() / 2; j < _battlefield_rgb[0].size(); j++)
			{
				_battlefield_rgb[i][j] = poscolor;
			}
		}
		poscolor++;
		for (int i = _battlefield_rgb.size() / 2; i < _battlefield_rgb.size(); i++)
		{
			for (int j = 0; j < _battlefield_rgb[0].size() / 2; j++)
			{
				_battlefield_rgb[i][j] = poscolor;
			}
		}
		poscolor++;
		for (int i = _battlefield_rgb.size() / 2; i < _battlefield_rgb.size(); i++)
		{
			for (int j = _battlefield_rgb[0].size() / 2; j < _battlefield_rgb[0].size(); j++)
			{
				_battlefield_rgb[i][j] = poscolor;
			}
		}
		poscolor++;
	}
	break;
	case 8:
	{
		for (int i = 0; i < 2; i++)
		{
			for (int j = 0; j < 4; j++)
			{
				// 绘制一个领地的颜色
				for (int k = 0; k < 16; k++)
				{
					for (int x = 0; x < 12; x++)
					{
						int row = i * 16 + k;
						int col = j * 12 + x;
						_battlefield_rgb[row][col] = poscolor;
					}
				}
				poscolor++;
			}
		}
	}
	break;
	default:

		break;
	}
}

class RequestCreateRoom : public Request
{
public:
	RequestCreateRoom() {}

	virtual bool Serialize(std::string *msg)
	{
		// Json::Value root;
		// root["server_type"] = CreateRoom;
		// Json::FastWriter writer;
		// *msg = writer.write(root);

		return true;
	}
	virtual bool Deserialize(const Json::Value &root)
	{
		_max_member = root["max_member"].asInt();
		InitBattlefieldColor(_max_member);
		InitCountDown(_max_member);
		return true;
	}

	int GetMaxMember() const
	{
		return _max_member;
	}

	~RequestCreateRoom() {}

private:
	int _max_member = 0;
};

class ResponseCreateRoom : public Response
{
public:
	ResponseCreateRoom()
	{
		srand((unsigned)time(nullptr));
	}

	virtual bool Serialize(std::string *msg)
	{
		Json::Value root;

		root["room_number"] = _room_number;
		Json::FastWriter writer;
		*msg = writer.write(root);
		_room_number.clear();
		return true;
	}

	bool ServerHandler(const RequestCreateRoom *req, Connection *conn)
	{
		// 生成不重复的非零的房间号
		// 创建一个随机数引擎（使用系统时钟作为种子）
		std::random_device rd;	// 用于生成随机种子
		std::mt19937 gen(rd()); // 以 rd() 作为种子的 Mersenne Twister 引擎

		// 创建一个均匀分布的整数生成器 ['0', '9']
		std::uniform_int_distribution<> dis('0', '9');
		while ((_room_number == "") || rooms.find(_room_number) != rooms.end())
		{
			std::string room_number;
			while (room_number.size() < 4)
			{
				room_number.push_back(dis(gen));
			}
			_room_number = room_number;
		}
		// _room_number = "9999";

		// 创建房间，增添第一个玩家，并且建立起文件描述符（玩家）与房间的映射
		rooms[_room_number] = new Room(_room_number, req->GetMaxMember());
		rooms[_room_number]->AddPlayer(conn);
		fd_to_room_number[conn->GetFd()] = _room_number;
		return true;
	}

	void ClearRoomNumber()
	{
		_room_number.clear();
	}

	// // virtual bool ServerHandler(const Request *req, int fd)
	// bool ServerHandler(const RequestCreateRoom *req, int fd)
	// {
	// 	// 生成不重复的非零的房间号
	// 	// int room_number = -1;
	// 	while (_room_number.size() < 4)
	// 	// while ((room_number == -1) || (rooms.find(std::to_string(room_number)) != rooms.end()) || room_number == 0)
	// 	{
	// 		_room_number.push_back((rand() % 10) + '0');
	// 	}
	// 	// _room_number = std::to_string(room_number);

	// 	// 创建房间，并且建立起文件描述符（玩家）与房间的映射
	// 	// RequestCreateRoom *createroomreq = (RequestCreateRoom *)req;
	// 	// std::cout << "createroomreq: " << createroomreq << std::endl;
	// 	// rooms.insert(std::make_pair(_room_number, new Room(_room_number, req->GetMaxMember())));
	// 	rooms[_room_number] =  new Room(_room_number, req->GetMaxMember());
	// 	// rooms.insert(std::make_pair(_room_number, new Room(_room_number, createroomreq->GetMaxMember())));
	// 	rooms[_room_number]->AddPlayer(fd);
	// 	// std::cout << "room_number: " << _room_number << std::endl;
	// 	fd_to_room_number[fd] = _room_number;
	// 	// std::cout << "room_number: " << _room_number << std::endl;
	// 	return true;
	// }

	virtual bool Deserialize(const std::string &result)
	{
		Json::Value root;
		Json::Reader reader;
		reader.parse(result, root);
		_room_number = root["room_number"].asInt();

		return true;
	}

	virtual ~ResponseCreateRoom() {}

private:
	std::string _room_number;
};